﻿using System;

namespace DevelopTool.Common
{
    /// <summary>
    /// 存储帮助类
    /// </summary>
    public class StorageHelper
    {
        #region 存储单位转换

        // 定义存储单位与比特（bit）的比例，作为基准
        private const long Bit = 1;
        private const long Byte = 8 * Bit;
        private const long Kilobyte = 1024 * Byte;
        private const long Megabyte = 1024 * Kilobyte;
        private const long Gigabyte = 1024 * Megabyte;
        private const long Terabyte = 1024 * Gigabyte;
        private const long Petabyte = 1024 * Terabyte;

        /// <summary>
        /// 转换方法
        /// </summary>
        /// <param name="value"></param>
        /// <param name="fromUnit"></param>
        /// <param name="toUnit"></param>
        /// <returns></returns>
        public static double ConvertStorage(double value, string fromUnit, string toUnit)
        {
            // 将值从原始单位转换为比特
            double valueInBits = value * GetUnitFactor(fromUnit);

            // 将比特值转换为目标单位
            return valueInBits / GetUnitFactor(toUnit);
        }

        // 获取单位对应的比特数
        private static long GetUnitFactor(string unit)
        {
            switch (unit.ToLower())
            {
                case "bit": return Bit;
                case "b": return Byte;
                case "kb": return Kilobyte;
                case "mb": return Megabyte;
                case "gb": return Gigabyte;
                case "tb": return Terabyte;
                case "pb": return Petabyte;
                default: throw new ArgumentException("Unknown storage unit.");
            }
        }

        #endregion 存储单位转换


        /// <summary>
        /// 字节转换成"B", "KB", "MB", "GB", "TB"实例
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FormatBytes(long bytes)
        {
            string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" };
            int i = 0;
            double dblSByte = bytes;
            if (bytes > 1024)
                for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
                    dblSByte = bytes / 1024.0;
            return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]);
        }
    }
}
